package com.lch.base.http.observer;

import com.lch.base.http.callback.ICallbackBase;
import com.lch.base.http.utils.LogUtils;
import com.lch.base.http.exception.ApiException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * ObserverBase
 *
 * @author lee(29487113@qq.com) on 18/2/4.
 */
class RxObserverBase<T> implements Observer<T> {
    private ICallbackBase mCallBack;
    private Object mTag;

    public RxObserverBase(ICallbackBase callBack) {
        super();
        if (callBack != null) {
            mCallBack = callBack;
            mTag = mCallBack.getTag();
        }
    }


    //当订阅后，会首先调用这个方法，其实就相当于onStart()，
    @Override
    public void onSubscribe(Disposable d) {
        LogUtils.i("---线程onSubscribe" + " => " + Thread.currentThread().getName());
        if (mCallBack != null) {
            mCallBack.onStart();
            mCallBack.onStart(mTag);
        }
    }

    @Override
    public void onNext(T data) {
        LogUtils.i("---线程onNext:" + " => " + Thread.currentThread().getName());
        if (mCallBack != null) {
            mCallBack.onSuccess(data);
            mCallBack.onSuccess(mTag, data);
        }
    }

    @Override
    public void onError(Throwable e) {
        LogUtils.i("---线程onError:" + " => " + Thread.currentThread().getName());
        if (e instanceof ApiException) {
            onErrorCustom((ApiException) e);
        } else {
            onErrorCustom(new ApiException(e));
        }
    }

    @Override
    public void onComplete() {
        LogUtils.i("---线程onComplete:" + " => " + Thread.currentThread().getName());
        if (mCallBack != null) {
            mCallBack.onCompleted();
            mCallBack.onCompleted(mTag);
            mCallBack.onReset();
        }
    }


    protected void onErrorCustom(ApiException e) {
        if (mCallBack != null) {
            mCallBack.onFail(e);
            mCallBack.onFail(mTag, e);
        }
    }
}
